package ithink.link.base.utils;

import com.codahale.metrics.*;
import ithink.link.base.influxdb.InfluxdbReporter;
import ithink.link.base.influxdb.api.protocols.HttpInfluxdbProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by zaqb on 17-11-26.
 */
public class InfluxdbHelper {
    public static final Logger LOGGER = LoggerFactory.getLogger( InfluxdbHelper.class);
    private static MetricRegistry registry = new MetricRegistry();

    public static Counter counter(Class<?> type, String name) {
        return registry.counter(getMonitorName(type, name));
    }

    public static void gauge(Class<?> type, String name, Gauge gauge) {
        registry.register(getMonitorName(type, name), gauge);
    }

    private static String getMonitorName(Class<?> type, String name) {
        if (type == null) {
            return MetricRegistry.name(getNamePrefix(), name);
        }
        return MetricRegistry.name(getNamePrefix() + type.getCanonicalName(), name);
    }

    private static String getNamePrefix()
    {
        return "";
    }

    public static MetricRegistry getRegistry()
    {
        return registry;
    }

    public static Histogram histogram(Class<?> type, String name)
    {
        return registry.histogram(getMonitorName(type, name));
    }

    public static void init(String ip, Integer port, String name) throws Exception {
        try {
            final InfluxdbReporter.Builder reporter = InfluxdbReporter.forRegistry(registry)
                    .protocol(new HttpInfluxdbProtocol(ip,port, "ithink"))
                    .convertRatesTo(TimeUnit.SECONDS)
                    .convertDurationsTo(TimeUnit.MILLISECONDS)
                    .filter(MetricFilter.ALL)
                    .tag("name", name)
                    .skipIdleMetrics(false);
            reporter.build().start(10,TimeUnit.SECONDS);
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("monitor config error", ex);
            throw new Exception("monitor config error");
        }
    }

    public static Meter meter(Class<?> type,String name) {
        return registry.meter(getMonitorName(type, name));
    }

    public static void remove(Class<?> type, String name)
    {
        registry.remove(getMonitorName(type, name));
    }

    public static Timer timer(Class<?> type, String name)
    {
        return registry.timer(getMonitorName(type, name));
    }

}
